package com.insigma.business.common.config;
import com.alibaba.fastjson.JSONObject;
import com.insigma.business.qrcode.common.vo.BaseResponseExtend;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;
import org.springframework.util.PatternMatchUtils;
import org.springframework.beans.factory.annotation.Value;

/**
 * @Author: huangjh
 * @description:
 * @date: 2024-05-14 16:24
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Value("${auth.excluded-urls}")
    private String excludedUrlsConfig;

    @Value("${server.servlet.context-path}")
    private String contextPath;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        SecurityContextHolder.clearContext();
        //检查请求是否包含有效的用户信息
        boolean isAuthenticated = StringUtils.isNotBlank(request.getHeader("vms-token"))
                && null != request.getSession()
                && StringUtils.isNotBlank(request.getSession().getId())
                && request.getHeader("vms-token").equals(request.getSession().getId())
                ;
        //如果用户未登录，并且请求的URI不在免校验列表中
        if (!isAuthenticated && !isExcludedUrl(request.getRequestURI())) {
            //设置响应状态码为401 Forbidden
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            //返回错误信息
            response.getWriter().write(JSONObject.toJSONString(BaseResponseExtend.error("当前登录信息异常")));
            return false;
        }
        return true;
    }

    //检查请求的URI是否在免校验列表中
    private boolean isExcludedUrl(String requestURI) {
        if (requestURI.startsWith(contextPath)) {
            requestURI = requestURI.substring(contextPath.length());
        }
        //从配置文件中读取
        String[] excludedUrls = excludedUrlsConfig.split(",");
        for (String excludedUrl : excludedUrls) {
            if (PatternMatchUtils.simpleMatch(excludedUrl, requestURI)) {
                return true;
            }
        }
        return false;
    }
}